module.exports = app => {
    const express = require('express')
    const AdminUser = require('../../models/AdminUser')
    const multer = require('multer')
    const jwt = require('jsonwebtoken')
    const assert = require('http-assert')
    const router = express.Router({
        mergeParams: true //合并参数
    })


    // 登录校验中间件
    const authMiddleware = require('../../middleware/auth')

    // 资源中间件
    const resourceMiddleware =  require('../../middleware/resource')


    //列表 
    router.get('/', async (req, res) => {
        let queryOptions = ''
        if (req.Model.modelName === 'Goods') {
            queryOptions = 'category'
        }
        // sort 根据字段名排序 1 正序 -1 倒序 sort({'_id': -1})
        //limit 查询的最大条数
        //skip 指定跳过的最大台数
        const model = await req.Model.find().populate(queryOptions)
        res.send(model)
    })

    // 增加
    router.post('/', async (req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    })

    // 删除
    router.delete('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndDelete(req.params.id)
        res.send({
            state: true
        })
    })

    // 修改
    router.put('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    // 查详情
    router.get('/:id', async (req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send(model)
    })

    // 查询用户
    router.post('/select', async (req, res) => {
        const model = await req.Model.find(req.body)
        res.send(model)
    })

    app.use('/admin/api/rest/:resource', authMiddleware(), resourceMiddleware(), router)

    // 上传图片
    const upload = multer({
        dest: __dirname + '/../../uploads',
    })

    app.post('/admin/api/upload', authMiddleware(), upload.single('file'), async (req, res) => {
        const file = req.file
        file.url = `http://localhost:3000/uploads/${file.filename}`
        res.send(file)
    })

    app.post('/admin/api/login', async (req, res) => {
        const {username, password} = req.body
        const user = await AdminUser.findOne({username}).select('+password')
        // 校验用户名
        assert(user, 422, '用户不存在')
        // 校验密码
        const isValid = require('bcrypt').compareSync(password, user.password)
        assert(isValid, 422, '密码错误')
        // 返回token
        const token = jwt.sign({id: user._id}, app.get('secret'))
        res.send({
            username: user.username,
            token: token
        })
    })
    // 错误处理
    app.use(async (err, req, res, next) => {
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}